package com.tongxin.van.frameworkcanary.utils;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.tongxin.van.frameworkcanary.bean.AlipayResult;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 *
 * author: VanyLiu
 * email: 13212674795@163.com
 * description:支付宝工具类
 *
**/
public class PayAlipayUtils {

    private static final String TAG = PayAlipayUtils.class.getSimpleName();

    public static void payAlipay(Activity activity, String orderInfo, PayCallBack payCallBack) {
        Observable
                .create((ObservableOnSubscribe<String>) emitter -> {
                    PayTask alipay = new PayTask(activity);
                    Map<String, String> resultMap = alipay.payV2(orderInfo, true);
                    final AlipayResult alipayResult = new AlipayResult(resultMap);
                    if (TextUtils.equals(alipayResult.getResultStatus(), "9000")) {
                        emitter.onNext(alipayResult.getResult());
                    } else {
                        emitter.onError(new Throwable(alipayResult.getResult()));
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String s) {
                        Log.d(TAG, "s" + s);
                        payCallBack.success("支付成功");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "e" + e.getMessage());
                        payCallBack.error("支付失败或取消" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public interface PayCallBack {
        public abstract void success(String msg);

        public abstract void error(String error);
    }
}
